import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class jdbcInsert {
    public static void main(String[] args) throws SQLException {
        Scanner sc=new Scanner(System.in);
        //创建并初始化数据源
        DataSource dataSource=new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/j2?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");
        //建立连接
        Connection connection= dataSource.getConnection();
        //写sql语句

        //通过控制台让用户输入
        System.out.println("请输入学生的姓名");
        String name=sc.nextLine();
        System.out.println("请输入学生的学号");
        int id=sc.nextInt();
        String sql="insert into student value(?,?)";
        PreparedStatement preparedStatement= connection.prepareStatement(sql); //预编译，减轻mysql服务器的负担

        preparedStatement.setInt(1,id);
        preparedStatement.setString(2,name);
        System.out.println(preparedStatement);
        //执行sql语句
        int ret=preparedStatement.executeUpdate();
        System.out.println("ret= "+ret);
        preparedStatement.close();;
        connection.close();

    }
}